# 创建时间:2023/2/12 0:02
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :Home.py
# 基于 Python 3.8.2
# ========================================
# 主界面
# ========================================
from typing import Union
import pygame
from pygame import freetype
from pygame.surface import Surface, SurfaceType

from Api import savings, uiApi
from BasePygame.Gamer import first, PageDict, SpriteSoldier, SpriteCommon, change_image, LoadImage, loadHalfImage, \
    imageLoad_from_plist
from BasePygame.Public import flagBox, fontDefault, fontB
from PyGameUI.Use.MusicBox import MusicBox
from PyGameUI.Use.SoldierPaths import SoldierPaths


class HomePage(PageDict):
    """首页"""

    def __init__(self, touch: SpriteCommon):
        """首页

        :param touch: 鼠标精灵
        """
        bgsurface = change_image(savings.kanbanBg)
        super().__init__(bgsurface)
        self.touch = touch
        self.soldierPaths = SoldierPaths(savings.kanban, savings.language)
        self.kanban = SpriteSoldier(savings.kanban, self.soldierPaths.initImage, 'half')
        self.kanban_image = self.kanban.image
        self.kanban_sound = None
        self.kanban_change_flag = False
        self.kanban_stay_t = pygame.time.get_ticks()
        self.musicBox = MusicBox()
        self.add(self.kanban, 'kanban')

        self.all_menuAdLoads = imageLoad_from_plist(*uiApi.getUiPathPlist('mainuilayer'))
        self.all_statusLoads = imageLoad_from_plist(*uiApi.getUiPathPlist('mainuilayer1'))
        self.all_buttonLoads = imageLoad_from_plist(*uiApi.getUiPathPlist('mainmenuitem'))
        self.all_commonlayer = imageLoad_from_plist(*uiApi.getUiPathPlist('commonlayer'))  # 各种公共元素
        self.all_topcurrencylayer = imageLoad_from_plist(*uiApi.getUiPathPlist('topcurrencylayer'))  # 紫砖、状态管、+/-
        self.choosed = None
        self.player = self.all_statusLoads['player']  # 左上角
        self.buttonbg = self.all_statusLoads['buttonbg']  # <按钮背景>
        self.enters = self.left_buttons = self.mid_buttons = self.down_buttons = self.menu_ad = self.status_addbtns = list()

        playerexp_path = uiApi.getUiPicture('playerexp')[0]
        playerexp = LoadImage(change_image(playerexp_path))
        playerexp.drag(0.5)
        self.player.draw_in(playerexp.surface, (120, 40))
        fontB.render_to(self.player.surface, (88, 12), savings.username, (255, 255, 255), size=28)
        fontB.render_to(self.player.surface, (0, 14), str(savings.userRank), 'white', style=freetype.STYLE_STRONG, size=30)

    def __del__(self):
        """销毁时处理"""
        for one in self.SurfaceDict:
            try:
                self.SurfaceDict.get(one).kill()
            except:
                continue
        del self.all_statusLoads, self.all_menuAdLoads, self.all_buttonLoads
        super().__del__()
        del self

    def get(self, key):
        """获取图片"""
        if key not in self.SurfaceDict:
            raise KeyError(f'键”{key}“不存在！当前键：{self.SurfaceDict.keys()}')
        surface: Union[Surface, SurfaceType, SpriteCommon]
        surface = self.SurfaceDict[key]
        return surface

    def drawAll(self):
        """绘制所有图像"""
        self.draw_bg()
        self.draw_status()
        flagBox.fondled_where = self.kanban.touchWhere(*self.touch.rect.topleft)
        flagBox.fondled = pygame.sprite.collide_mask(self.touch, self.kanban)
        self.draw_kanban()
        self.draw_buttons()
        self.draw_menuAd()
        self.checks()

    def draw_bg(self):
        """绘制背景：背景图、用户左上角、入口"""
        screen = self.screen
        screen.blit(self.bg, (0, 0))
        resourcebg2_path = uiApi.getUiPicture('resourcebg2')[0]

        all_statusLoads = self.all_statusLoads
        war = all_statusLoads['war']  # 无字 进入战役
        activityd = all_statusLoads['activityd']  # 无字 活动副本
        activitydno = all_statusLoads['activitydno']  # 有字 禁用 活动副本
        arena = all_statusLoads['arena']  # 无字 演习场
        arenano = all_statusLoads['arenano']  # 有字 禁用 演习场
        dispatch = all_statusLoads['dispatch']  # 无字 派遣
        dispatchno = all_statusLoads['dispatchno']  # 有字 禁用 派遣
        name1 = all_statusLoads['name1']  # "进入战役"
        name2 = all_statusLoads['name2']  # "活动副本"
        name3 = all_statusLoads['name3']  # "演习场"
        name7 = all_statusLoads['name7']  # "派遣"

        self.enters = [war, dispatch, arena, activityd]  # 进入战役、派遣、演习场、活动副本
        screen.blit(change_image(resourcebg2_path), (0, 0))

        # player.draw_in(userLevel, (0, 8))
        # player.draw_in(username, (88, 10))
        screen.blit(self.player.surface, (0, 0))

        war.draw_in_center(name1)
        war.setTopleft((738, 218))
        screen.blit(war.surface, war.rect)

        arena.draw_in_center(name3)
        arena.setTopleft((738, 389))
        screen.blit(arena.surface, arena.rect)

        dispatch.draw_in_center(name7)
        dispatch.setTopleft((1016, 218))
        screen.blit(dispatch.surface, dispatch.rect)

        activityd.draw_in_center(name2)
        activityd.setTopleft((924, 389))
        screen.blit(activityd.surface, activityd.rect)
        # ===========连接函数==========
        war.connect(self.click_war)
        arena.connect(self.click_arena)
        dispatch.connect(self.click_dispatch)
        activityd.connect(self.click_activityd)

    def draw_status(self):
        """绘制顶部状态栏：体力、小钱钱、金条"""
        screen = self.screen
        all_commonlayer = self.all_commonlayer  # 各种公共元素
        all_topcurrencylayer = self.all_topcurrencylayer  # 紫砖、状态管、+/-

        progressbg1 = all_topcurrencylayer['progressbg1']  # 长状态管
        progressbg2 = all_topcurrencylayer['progressbg2']  # 短状态管
        currencyamethyst = all_topcurrencylayer['currencyamethyst']  # 紫砖
        bp = all_topcurrencylayer['bp']  # bp图标
        bp1 = all_topcurrencylayer['bp1']  # 空bp
        addbutton = all_topcurrencylayer['addbutton']  # +
        addbutton2 = all_topcurrencylayer['addbutton2']  # + 禁用
        maxfont = all_topcurrencylayer['max']  # max文案
        reply = all_topcurrencylayer['reply']  # 回复 文案

        btn_return = all_commonlayer['return']  # 返回按钮
        maxicon = all_commonlayer['max']  # max图标
        money = all_commonlayer['money']  # 小钱钱
        gem = all_commonlayer['gem']  # 金条
        actionpoint = all_commonlayer['actionpoint']  # 甜甜圈

        actionpointpgpath = uiApi.getUiPicture('actionpointpg')[0]
        times = min(savings.actionPoint / (savings.userRank + 50), 1)
        actionpointpg = LoadImage(change_image(actionpointpgpath)).drag(times).setTopleft((485, 10))  # 体力条

        actionpoint_bg = progressbg1.copy().setTopleft((485, 10))
        screen.blit(actionpoint_bg.surface, actionpoint_bg.rect)
        screen.blit(actionpointpg.surface, actionpointpg.rect)

        money_bg = progressbg2.copy().setTopleft((717, 10))
        screen.blit(money_bg.surface, money_bg.rect)
        gem_bg = progressbg1.copy().setTopleft((913, 10))
        screen.blit(gem_bg.surface, gem_bg.rect)

        actionpoint.setTopleft((461, 1))
        screen.blit(actionpoint.surface, actionpoint.rect)
        money.setTopleft((693, 1))
        screen.blit(money.surface, money.rect)
        gem.setTopleft((888, 1))
        screen.blit(gem.surface, gem.rect)

        actionpoint_add = addbutton.copy().setTopleft((633, 1))
        screen.blit(actionpoint_add.surface, actionpoint_add.rect)
        gem_add = addbutton.copy().setTopleft((1061, 1))
        screen.blit(gem_add.surface, gem_add.rect)
        self.status_addbtns = [actionpoint_add, gem_add]
        actionpoint_add.connect(self.click_actionpoint_add)
        gem_add.connect(self.click_gem_add)

        actionpoint_now = f'{savings.actionPoint}/{savings.userRank + 50}'
        fontDefault.render_to(self.screen, (519, 16), actionpoint_now, (255, 255, 255), size=20)
        fontDefault.render_to(self.screen, (760, 16), str(savings.money), (255, 255, 255), size=20)
        fontDefault.render_to(self.screen, (988, 16), str(savings.gem), (255, 255, 255), size=20)

    def draw_kanban(self):
        """绘制看板娘"""
        if self.kanban_change_flag:
            self.kanban.change(self.kanban_image)
            if self.kanban_sound: self.musicBox.playMusic(self.kanban_sound)
            self.kanban_sound = None
            self.kanban_change_flag = False
            self.kanban_stay_t = pygame.time.get_ticks()
        kanbanRect = self.kanban.rect
        kanbanRect.midleft = self.screen_sizeRect.midleft
        self.screen.blit(self.kanban.image, kanbanRect)

    def draw_buttons(self):
        """绘制按钮（左侧按钮、底部按钮、右侧按钮）"""
        screen = self.screen
        mainmenu_bg3path = uiApi.getUiPicture('mainmenu_bg3')[0]
        mainmenu_bg3 = LoadImage(change_image(mainmenu_bg3path))
        mainmenu_bg3.rect.bottomright = first.screen_sizeRect.bottomright
        screen.blit(mainmenu_bg3.surface, mainmenu_bg3.rect)

        all_buttons = self.all_buttonLoads
        announcement = all_buttons['announcement']  # 公告
        announcement2 = all_buttons['announcement2']
        blackmarket = all_buttons['blackmarket']  # 黑市
        blackmarket2 = all_buttons['blackmarket2']
        directory = all_buttons['directory']  # 宿舍
        directory2 = all_buttons['directory2']
        formation = all_buttons['formation']  # 编队
        formation2 = all_buttons['formation2']
        friend = all_buttons['friend']  # 萌友
        friend2 = all_buttons['friend2']
        general = all_buttons['general']  # 编成
        general2 = all_buttons['general2']
        mailbox = all_buttons['mailbox']  # 邮件
        mailbox2 = all_buttons['mailbox2']
        shop = all_buttons['shop']  # 商店
        shop2 = all_buttons['shop2']
        soldiers = all_buttons['soldiers']  # 培养
        soldiers2 = all_buttons['soldiers2']
        task = all_buttons['task']  # 任务
        task2 = all_buttons['task2']
        rank = all_buttons['rank']  # 纪录榜
        rank2 = all_buttons['rank2']
        society = all_buttons['society']  # 军团
        society2 = all_buttons['society2']

        bossicon = all_buttons['bossicon']  # boss特殊任务
        allocationbutton = all_buttons['allocationbutton']  # 期间任务
        signbutton = all_buttons['signbutton']  # 累计登录
        novicetaskbutton = all_buttons['novicetaskbutton']  # 训练手册
        friendbossbutton = all_buttons['friendbossbutton']  # 萌友特殊任务

        general = general.drawed_in_center(self.buttonbg.copy())
        soldiers = soldiers.drawed_in_center(self.buttonbg.copy())
        directory = directory.drawed_in_center(self.buttonbg.copy())
        blackmarket = blackmarket.drawed_in_center(self.buttonbg.copy())
        shop = shop.drawed_in_center(self.buttonbg.copy())
        friend = friend.drawed_in_center(self.buttonbg.copy())
        society = society.drawed_in_center(self.buttonbg.copy())

        self.left_buttons = [announcement, mailbox, task, rank]  # 公告/邮件/任务/记录榜
        self.mid_buttons = [bossicon, allocationbutton, signbutton]  # boss特殊任务/期间任务/累计登录/萌友特殊任务
        # self.mid_buttons.append(friendbossbutton)  # boss特殊任务/期间任务/累计登录/萌友特殊任务
        self.down_buttons = [general, soldiers, directory, blackmarket, shop, friend, society]  # 编成/培养/宿舍/黑市/商店/萌友/军团

        # temp_set = lambda s, loc: s.setTopleft(loc) if s.rect.topleft == (0, 0) else ...
        announcement.setTopleft((9, 106))
        for index, btn in enumerate(self.left_buttons):
            if index == 0:
                screen.blit(btn.surface, btn.rect)
                continue
            btn.setTopleft(self.left_buttons[index - 1].rect.copy().move(0, 100).topleft)
            screen.blit(btn.surface, btn.rect)

        bossicon.setTopleft((644, 83))
        for index, btn in enumerate(self.mid_buttons):
            if index == 0:
                screen.blit(btn.surface, btn.rect)
                continue
            btn.setTopleft(self.mid_buttons[index - 1].rect.copy().move(0, 100).topleft)
            screen.blit(btn.surface, btn.rect)

        general.setTopleft((31, 546))
        for index, btn in enumerate(self.down_buttons):
            if index == 0:
                screen.blit(btn.surface, btn.rect)
                continue
            btn.setTopleft(self.down_buttons[index - 1].rect.copy().move(140, 0).topleft)
            # btn.rect = down_buttons[index - 1].rect.copy().move(140, 0)
            screen.blit(btn.surface, btn.rect)
        # ===========连接函数==========
        announcement.connect(self.click_announcement)
        mailbox.connect(self.click_mailbox)
        task.connect(self.click_task)
        rank.connect(self.click_rank)

        bossicon.connect(self.click_bossicon)
        allocationbutton.connect(self.click_allocationbutton)
        signbutton.connect(self.click_signbutton)
        friendbossbutton.connect(self.click_friendbossbutton)
        # print('连接底部按钮......')
        general.connect(self.click_general)
        soldiers.connect(self.click_soldiers)
        directory.connect(self.click_directory)
        blackmarket.connect(self.click_blackmarket)
        shop.connect(self.click_shop)
        friend.connect(self.click_friend)
        society.connect(self.click_society)

    def draw_menuAd(self):
        """绘制：menu、广告轮播图"""
        screen = self.screen
        all_menuAdLoads = self.all_menuAdLoads
        menu = all_menuAdLoads['menu']  # menu菜单
        menu2 = all_menuAdLoads['menu2']  # menu菜单 带锁
        xian = all_menuAdLoads['xian']  # 细长的一条竖线（无用）
        line = all_menuAdLoads['line']  # 横宽透明图（无用）
        _1 = all_menuAdLoads['1']  # 灰色背景宽图（像是对话框）
        nor = all_menuAdLoads['nor']  # 空面板 无边框
        adboxr = all_menuAdLoads['adboxr']  # 广告边框

        self.menu_ad = [menu, adboxr]
        menu.setTopleft((1030, 580))
        screen.blit(menu.surface, menu.rect)

        adboxr.draw_in(nor.surface, (5, 5))
        adboxr.setTopleft((738, 80))
        screen.blit(adboxr.surface, adboxr.rect)
        # ===========连接函数==========
        menu.connect(self.click_menu)
        adboxr.connect(self.click_adbox)

    def checks(self):
        """执行检查点击"""
        if self.enters:
            for enter in self.enters:
                if enter.check('buttonLock')[0]: return
        if self.left_buttons:
            for one in self.left_buttons:
                if one.check('buttonLock')[0]: return
        if self.mid_buttons:
            for one in self.mid_buttons:
                if one.check('buttonLock')[0]: return
        if self.down_buttons:
            for one in self.down_buttons[:2] + self.down_buttons[4:]:
                if one.check('buttonLock')[0]: return
            if self.down_buttons[2].check('buttonNormal')[0]: return
            if self.down_buttons[3].check('buttonNormal')[0]: return
        if self.menu_ad:
            for one in self.menu_ad:
                if one.check('buttonLock')[0]: return
        if self.status_addbtns:
            for one in self.status_addbtns:
                if one.check('buttonNormal')[0]: return

        if any(flagBox.clickOnce) and flagBox.fondled and flagBox.where_in is None:
            flagBox.where_in = 'kanban'
        if flagBox.clicked and flagBox.fondled_where and flagBox.fondled:
            face, self.kanban_sound = self.soldierPaths.touch_feedback()
            self.kanban_image = loadHalfImage(*face, self.soldierPaths.initImage).surface
            self.kanban_change_flag = True
            self.kanban_stay_t = pygame.time.get_ticks()
            return
        elif pygame.time.get_ticks() - self.kanban_stay_t > 90_000:
            face, self.kanban_sound = self.soldierPaths.random_talk()
            self.kanban_image = loadHalfImage(*face, self.soldierPaths.initImage).surface
            self.kanban_change_flag = True
            self.kanban_stay_t = pygame.time.get_ticks()
            return

    # [war, dispatch, arena, activityd]  # 进入战役、派遣、演习场、活动副本
    def click_war(self):
        """点击了【进入战役】"""
        print("点击了【进入战役】")

    def click_dispatch(self):
        """点击了【派遣】"""
        print("点击了【派遣】")

    def click_arena(self):
        """点击了【演习场】"""
        print("点击了【演习场】")

    def click_activityd(self):
        """点击了【活动副本】"""
        print("点击了【活动副本】")

    # [announcement, mailbox, task, rank] 公告/邮件/任务/记录榜
    def click_announcement(self):
        """点击了【公告】"""
        print("点击了【公告】")

    def click_mailbox(self):
        """点击了【邮件】"""
        print("点击了【邮件】")

    def click_task(self):
        """点击了【任务】"""
        print("点击了【任务】")

    def click_rank(self):
        """点击了【记录榜】"""
        print("点击了【记录榜】")

    # [bossicon, allocationbutton, signbutton, friendbossbutton]  # boss特殊任务/期间任务/累计登录/萌友特殊任务
    def click_bossicon(self):
        """点击了【boss特殊任务】"""
        print("点击了【boss特殊任务】")

    def click_allocationbutton(self):
        """点击了【期间任务】"""
        print("点击了【期间任务】")

    def click_signbutton(self):
        """点击了【累计登录】"""
        print("点击了【累计登录】")

    def click_friendbossbutton(self):
        """点击了【萌友特殊任务】"""
        print("点击了【萌友特殊任务】")

    # [general, soldiers, directory, blackmarket, shop, friend, society]  # 编成/培养/宿舍/黑市/商店/萌友/军团
    def click_general(self):
        """点击了【编成】"""
        print("点击了【编成】")

    def click_soldiers(self):
        """点击了【培养】"""
        print("点击了【培养】")

    def click_directory(self):
        """点击了【宿舍】"""
        print("点击了【宿舍】")
        flagBox.herePageClickTo = 'directory'

    def click_blackmarket(self):
        """点击了【黑市】"""
        print("点击了【黑市】")

    def click_shop(self):
        """点击了【商店】"""
        print("点击了【商店】")

    def click_friend(self):
        """点击了【萌友】"""
        print("点击了【萌友】")

    def click_society(self):
        """点击了【军团】"""
        print("点击了【军团】")

    def click_menu(self):
        """点击了【menu】"""
        print("点击了【menu】")

    def click_adbox(self):
        """点击了【广告】"""
        print("点击了【广告】")

    def click_actionpoint_add(self):
        """点击了【添加体力】"""
        print("点击了【添加体力】")

    def click_gem_add(self):
        """点击了【添加金条】"""
        print("点击了【添加金条】")
